import React, { Component, useState, useEffect, Fragment } from 'react';
import axios from 'axios';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Button,
  Table,
  Icon,
  Divider,
  Popconfirm,
  Spin,
  Form,
  Modal,
  Input,
  InputNumber,
  Radio,
  Select,
  DatePicker,
  message,
  Upload,
  Card,
  Tag,
} from 'antd';
import { router } from 'umi';
import { connect } from 'dva';
import { getParam } from '@/utils/utils';
import { isEqual } from 'lodash'
import RouterWillLeave from "@/components/RouterWillLeave";

function getToken() {
  const token = localStorage.getItem('token');
  return token;
}
import testModal from '@/assets/crmTable.xlsx';
import moment from 'moment';
let AddList = Form.create()(props => {
  const [scope, setScope] = useState('');
  const [productVisible, setproductVisible] = useState(false);
  const [list, setlist] = useState([]);
  const [Modaltotal, settotal] = useState(0);
  const [selectedRowKeys, setselectedRowKeys] = useState([]);
  const [goodslist, setgoodslist] = useState([]);
  const [goodslists, setgoodslists] = useState([]);
  const [fileLists, setfileLists] = useState([]);
  const [FromExcel, setFromExcel] = useState([]);
  const [Conditions, setConditions] = useState(null);
  const [currentTotls, setcurrentTotls] = useState(1);
  const [InputChan, setInputChan] = useState(null);
  const [SelectAll, setSelectAll] = useState([]);
  const [tags, setTags] = useState([]);
  const [current, setcurrent] = useState({});
  const [selecthand, setSelecthand] = useState([]);
  const [SelectAllSopt, setSelectAllSopt] = useState([]);
  const [keyWord, setkeyWord] = useState(false);
  let [typeStatus, setTypeStatus] = useState('SINGLE');
  let [packageId, setPackageId] = useState(null);
  const [isSubmit, setIsSubmit] = useState(false);
  const [originValues, setOriginValues] = useState({});
  
  const FormItem = Form.Item;
  const RadioGroup = Radio.Group;
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const { Search } = Input;

  const {
    form: { getFieldDecorator, getFieldValue, getFieldsValue,  validateFields },
    isFormModal,
    loading,
    // productList,
    handleSubmit,
    onCancel,
  } = props;
  useEffect(() => {
    props.dispatch({
      type: 'coupons/getSelectAlls',
      callback: res => {
        if (res.responseType === 'SUCCESS') {
          setSelectAll(res.data);
        } else {
          message.error(res.errorCode);
        }
      },
    });
  }, []);

  useEffect(() => {
    if (getParam('id')) {
      props.dispatch({
        type: 'coupons/getUpdatePageData',
        payload: { id: getParam('id') },
        callback: res => {
          setcurrent(res.data);
          setTypeStatus(res.data.type || 'SINGLE');
          setPackageId(res.data.packageId);
          // setrangeValues(res.data.rangeValues);
          // setphones(res.data.phones);

          if (res.data.rangeList) {
            setTags(res.data.rangeList);
          }
          setScope(res.data.rangeType);
        },
      });
    }
  }, []);
  
  useEffect(() => {
    const values = getFieldsValue()
    setOriginValues(values)
  }, []);

  let isDisabled = (props.location.state && props.location.state.isDisabled) || false;
  // let current = (props.location.state && props.location.state.current) || {};
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
      md: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
      md: { span: 17 },
    },
  };

  const validataDate = (rule, value, callback) => {
    if (getFieldValue('type') === '0' && (!value || !value.length)) {
      callback('请选择日期');
    }
    callback();
  };
  const onSelecthandleChange = e => {
    console.log(e);
    //    axios(`/hzsx/category/checkedProduct?keyWord=${e}&pageNumber=1&pageSize=10`, {
    //   method: 'POST', data: formdata
    // }).then((res) => {
    //   if (res.data.msg === '操作成功') {
    //     setFromExcel(res.data.data)
    //     message.success('导入成功')
    //   } else {
    //     message.error(res.data.msg)
    //   }
    // })
    setSelecthand(e);
  };
  const typeStatusChange = (value) => {
    setTypeStatus(value);
  };
  const onTj = () => {
    let selecthandArr = [];
    for (let i = 0; i < selecthand.length; i++) {
      selecthandArr.push(JSON.parse(selecthand[i]));
    }
    let arr = tags.concat(selecthandArr);
    var result = [];
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
      if (!obj[arr[i].productId]) {
        result.push(arr[i]);
        obj[arr[i].productId] = true;
      } else {
        result.push(arr[i]);
      }
    }
    let arr23 = result.filter(item => !item.description);
    let newArr = [];
    result.forEach(item => {
      let obj1 = {};
      for (let i = 0; i < arr.length; i++) {
        if (item.description) {
          obj1.productName = item.description;
          obj1.productId = item.value;
        } else {
          return;
        }
      }
      newArr.push(obj1);
    });
    let arr10 = newArr.concat(arr23);
    var result1 = [];
    var obj2 = {};
    for (var i = 0; i < arr10.length; i++) {
      if (!obj2[arr10[i].productId]) {
        result1.push(arr10[i]);
        obj2[arr10[i].productId] = true;
      }
    }
    props.form.setFieldsValue({ userRange11: result1 });
    setTags(result1);
  };
  const onQk = () => {
    props.form.setFieldsValue({ userRange11: [] });
    setTags([]);
  };
  const validatorGeographic = (rule, value, callback) => {
    if (value.length === 0) {
      callback('请选择指定商品!');
      return;
    }
    callback();
  };
  const handleClose = removedTag => {
    let tagData = tags
    const tagss = tagData.filter(tag => tag !== removedTag);
    console.log(tagss,'tagsstagss')
    props.form.setFieldsValue({ userRange11: tagss });
    setTags(tagss);
  };
  const okHandle = e => {
    e.preventDefault();
    validateFields((err, fieldsValue) => {
      if (err) return;
      handleSubmit(fieldsValue);
    });
  };
  const onThes = e => {
    setScope(e.target.value);
    if (scope === '') {
      setgoodslist([]);
      setgoodslists([]);
      setselectedRowKeys([]);
    }
  };

  const handleAddProduct = () => {
    props.dispatch({
      type: 'coupons/getGoods',
      payload: {
        pageNumber: 1,
        pageSize: 10,
      },
      callback: res => {
        if (res.data.msg === '操作成功') {
          message.success('获取信息成功');
          setlist(res.data.data.records);
          settotal(res.data.data.total);
        } else {
          message.error(res.data.msg);
        }
      },
    });
    setproductVisible(true);
  };
  const onShowModal = () => {
    setproductVisible(false);
  };
  const onSelectOk = () => {
    let listchul = [];
    for (let i = 0; i < goodslist.length; i++) {
      listchul.push({
        value: goodslist[i].productId,
        description: `${goodslist[i].name}`,
      });
    }
    setgoodslists(listchul);
    setproductVisible(false);
  };
  const onSelectChange = (selectedRowKeys, i) => {
    setselectedRowKeys(selectedRowKeys);
    setgoodslist(i);
  };
  const handleChange = file => {
    let formdata = new FormData();
    formdata.append('file', file);
    axios(`/hzsx/couponTemplate/readPhoneFromExcel`, {
      method: 'POST',
      headers: { token: getToken() },
      data: formdata,
    }).then(res => {
      console.log('res', res);
      if (res.data.responseType === 'SUCCESS') {
        setFromExcel(res.data.data);
        message.success('导入成功');
      } else {
        message.error('导入失败');
      }
    });
  };

  const onConditions = e => {
    setConditions(e.target.value);
  };

  const onSear = e => {
    setkeyWord(true);
    axios(`/hzsx/index/ableProductV1?keyWord=${e}&pageNumber=1&pageSize=10`, {
      method: 'get',
      headers: { token: getToken() },
    }).then(res => {
      if (res) {
        setkeyWord(false);
        message.success('查询成功！');
        if (res && res.data && res.data.data && res.data.data.records) {
          setSelectAllSopt(res.data.data.records);
        } else {
          setSelectAllSopt([]);
        }
      } else {
        message.error(res.data.msg);
      }
    });
  };
  const handleSubmits = e => {
    e.preventDefault();
    if (getParam('id')) {
      validateFields((err, values) => {
        if (!err) {
          setIsSubmit(true)
          if (values.userRange11) {
            const { userRange11 } = values;
            let listchulss = [];
            for (let i = 0; i < userRange11.length; i++) {
              if (userRange11[i].description) {
                listchulss.push({
                  value: userRange11[i].value,
                  description: userRange11[i].description,
                });
              } else {
                listchulss.push({
                  value: userRange11[i].productId,
                  description: userRange11[i].productName,
                });
              }
            }

            if (getFieldValue('type') === 1) {
              props.dispatch({
                type: 'coupons/modify',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  type: values.type2,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  delayDayNum: values.delayDayNum,
                  phones: FromExcel,
                  userRange: values.userRange,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: listchulss,
                  rangeType: values.rangeTypess,
                  id: getParam('id'),
                },
              });
            } else {
              props.dispatch({
                type: 'coupons/modify',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  startTime: moment(values.startEnd[0]).format('YYYY-MM-DD hh:mm:ss'),
                  endTime: moment(values.startEnd[1]).format('YYYY-MM-DD hh:mm:ss'),
                  phones: FromExcel,
                  userRange: values.userRange,
                  type: values.type2,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: listchulss,
                  rangeType: values.rangeTypess,
                  id: getParam('id'),
                },
              });
            }
          } else {
            if (getFieldValue('type') === 1) {
              props.dispatch({
                type: 'coupons/modify',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  type: values.type2,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  delayDayNum: values.delayDayNum,
                  phones: FromExcel,
                  userRange: values.userRange,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: goodslists,
                  rangeType: values.rangeTypess,
                  id: getParam('id'),
                },
              });
            } else {
              props.dispatch({
                type: 'coupons/modify',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  startTime: moment(values.startEnd[0]).format('YYYY-MM-DD hh:mm:ss'),
                  endTime: moment(values.startEnd[1]).format('YYYY-MM-DD hh:mm:ss'),
                  phones: FromExcel,
                  userRange: values.userRange,
                  status: values.status,
                  type: values.type2,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: goodslists,
                  rangeType: values.rangeTypess,
                  id: getParam('id'),
                },
              });
            }
          }
        }
      });
    } else {
      validateFields((err, values) => {
        console.log('values:', values);
        if (!err) {
          if (values.userRange11) {
            const { userRange11 } = values;
            let listchulss = [];
            for (let i = 0; i < userRange11.length; i++) {
              if (userRange11[i].description) {
                listchulss.push({
                  value: userRange11[i].value,
                  description: userRange11[i].description,
                });
              } else {
                listchulss.push({
                  value: userRange11[i].productId,
                  description: userRange11[i].productName,
                });
              }
            }
            if (getFieldValue('type') === 1) {
              console.log('liangansdkjlnbqskjdnaskljdnkljasndkjbns1');
              props.dispatch({
                type: 'coupons/couponAdd',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  type: values.type2,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  delayDayNum: values.delayDayNum,
                  phones: FromExcel,
                  userRange: values.userRange,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: listchulss,
                  rangeType: values.rangeTypess,
                },
              });
            } else {
              console.log('liangansdkjlnbqskjdnaskljdnkljasndkjbns2');
              props.dispatch({
                type: 'coupons/couponAdd',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  type: values.type2,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  startTime: moment(values.startEnd[0]).format('YYYY-MM-DD hh:mm:ss'),
                  endTime: moment(values.startEnd[1]).format('YYYY-MM-DD hh:mm:ss'),
                  phones: FromExcel,
                  userRange: values.userRange,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: listchulss,
                  rangeType: values.rangeTypess,
                },
              });
            }
          } else {
            if (getFieldValue('type') === 1) {
              console.log(values, 'asdasdasd');
              props.dispatch({
                type: 'coupons/couponAdd',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  delayDayNum: values.delayDayNum,
                  phones: FromExcel,
                  type: values.type2,
                  userRange: values.userRange,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: goodslists,
                  rangeType: values.rangeTypess,
                },
              });
            } else {
              props.dispatch({
                type: 'coupons/couponAdd',
                payload: {
                  title: values.title,
                  scene: values.scene,
                  displayNote: values.displayNote,
                  num: values.num,
                  type: values.type2,
                  minAmount: values.minAmount === '0' ? 0 : values.minPurchase,
                  // minAmount: values.minAmount,
                  userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
                  startTime: moment(values.startEnd[0]).format('YYYY-MM-DD hh:mm:ss'),
                  endTime: moment(values.startEnd[1]).format('YYYY-MM-DD hh:mm:ss'),
                  phones: FromExcel,
                  userRange: values.userRange,
                  status: values.status,
                  discountAmount: values.discountAmount,
                  forPackage: values.forPackage,
                  rangeList: goodslists,
                  rangeType: values.rangeTypess,
                },
              });
            }
          }
        }
      });
    }
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const columns = [
    {
      title: 'id',
      dataIndex: 'value',
    },
    {
      title: '名字',
      dataIndex: `description`,
      render: description => {
        return <>{description.split('/')[0]}</>;
      },
    },
    {
      title: '店铺名称',
      render: e => {
        return <>{e.description.split('/')[1]}</>;
      },
    },
  ];
  const Modalcolumns = [
    {
      title: '商品ID',
      dataIndex: 'productId',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
    },
    {
      title: '店铺名称',
      dataIndex: 'shopName',
    },
  ];
  const validateMinAmount = (rule, value, callback)=>{
    if(value === '0'){
      callback()
    }else if(value === '1'){
      const val = props.form.getFieldsValue()
      if (val.minPurchase) {
        callback()
      } else {
        callback('不可为空')
      }
    }
  }
  const onIdChang = e => {
    setcurrentTotls(e.current);
    props.dispatch({
      type: 'coupons/getGoods',
      payload: {
        pageNumber: e.current,
        pageSize: 10,
        productId: InputChan,
      },
      callback: res => {
        if (res.data.msg === '操作成功') {
          setlist(res.data.data.records);
          settotal(res.data.data.total);
        } else {
          message.error(res.data.msg);
        }
      },
    });
  };
  const onInputChan = e => {
    setInputChan(e.target.value);
  };

  const onSearch = () => {
    props.dispatch({
      type: 'coupons/getGoods',
      payload: {
        pageNumber: 1,
        pageSize: 10,
        productId: InputChan,
      },
      callback: res => {
        if (res.data.msg === '操作成功') {
          setlist(res.data.data.records);
          settotal(res.data.data.total);
        } else {
          message.error(res.data.msg);
        }
      },
    });
  };
  const onCategory = e => {
    let listchuls = [];
    for (let i = 0; i < e.length; i++) {
      listchuls.push({
        value: JSON.parse(e[i]).id,
        description: JSON.parse(e[i]).name,
      });
    }
    setgoodslists(listchuls);
  };
  const onUpload = info => {
    if (info.fileList.length === 0) {
      setfileLists([]);
    } else {
      setfileLists([info.fileList[info.fileList.length - 1]]);
    }
  };
  
  const handleCancel = () => {
    router.push('/Marketing/Coupon/list')
  }
  console.log(tags, 'tags:');
  
  const renderRouterWillLeave = () =>{
    const values = getFieldsValue()
    const isPrompt = !isEqual(values, originValues)
    return (
      <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit}  />
    )
  }

  return (
    <PageHeaderWrapper title="增加优惠券">
      {
        renderRouterWillLeave()
      }
      <Card style={{ marginBottom: 30 }}>
        <Spin spinning={false}>
          <Form onSubmit={handleSubmits}>
            <FormItem {...formItemLayout} label="用法" required>
              {getFieldDecorator('type2', {
                // rules: [{ required: true, message: '请选择用法' }],
                initialValue: current.type || 'SINGLE',
              })(
                <Select placeholder="请选择" onChange={ typeStatusChange }>
                  <Option value="SINGLE">独立使用</Option>
                  <Option value="PACKAGE">大礼包</Option>
                  <Option value="ACTIVITY">营销活动</Option>
                  <Option value="ALIPAY">支付宝券码券</Option>
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券类别" required>
              {getFieldDecorator('scene', {
                rules: [{ required: true, message: '请选择优惠券' }],
                initialValue: current.scene,
              })(
                <Select placeholder="请选择">
                  <Option value={'RENT'}>租赁</Option>
                  <Option value={'BUY_OUT'}>买断</Option>
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券名称" required>
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入优惠券名称' }],
                initialValue: current.title,
              })(<Input placeholder="请输入优惠券名称" disabled={isDisabled} />)}
            </FormItem>
            {
              typeStatus === 'SINGLE' || typeStatus === 'ACTIVITY' || typeStatus === 'ALIPAY'
                ? (
                  <FormItem {...formItemLayout} label="发放总量" required>
                    {getFieldDecorator('num', {
                      rules: [{ required: true, message: '请输入发放总量' }],
                      initialValue: current.num,
                    })(<InputNumber placeholder="请输入发放总量" style={{ width: '90%' }} />)}
                    &nbsp;张
                  </FormItem>
                )
                : ''
            }
            <FormItem {...formItemLayout} label="面额" required>
              {getFieldDecorator('discountAmount', {
                rules: [{ required: true, message: '请输入面额' }],
                initialValue: current.discountAmount,
              })(
                <InputNumber
                  disabled={isDisabled}
                  placeholder="请输入面额"
                  style={{ width: '90%' }}
                />,
              )}
              &nbsp;元
            </FormItem>
            <FormItem {...formItemLayout} label="使用条件" required>
              {getFieldDecorator('minAmount', {
                rules: [
                  { required: true, message: '请输入面额' },
                  { validator: validateMinAmount }
                ],
                initialValue: current.minAmount === 0 ? '0' : '1',
              })(
                <RadioGroup>
                  <Radio disabled={isDisabled} value="0">
                    不限制
                  </Radio>
                  <Radio disabled={isDisabled} value="1">
                    满&nbsp;
                    {getFieldDecorator('minPurchase', {
                      initialValue: current.minAmount || 1,
                    })(
                      <InputNumber
                        min={0}
                        precision={2}
                        disabled={getFieldValue('minAmount') === '0' || isDisabled}
                      />,
                    )}
                    &nbsp;元
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem>
            {
              typeStatus === 'SINGLE' || typeStatus === 'ACTIVITY' || typeStatus === 'ALIPAY'
                ? (
                  <FormItem {...formItemLayout} required label="每人限领">
                    {getFieldDecorator('userLimitNum', {
                      initialValue: current.userLimitNum || 0,
                    })(
                      <Select>
                        <Option value={0}>无限制</Option>
                        <Option value={1}>1张</Option>
                        <Option value={2}>2张</Option>
                        <Option value={3}>3张</Option>
                        <Option value={4}>4张</Option>
                        <Option value={5}>5张</Option>
                        <Option value={6}>6张</Option>
                        <Option value={7}>7张</Option>
                        <Option value={8}>8张</Option>
                        <Option value={9}>9张</Option>
                        <Option value={10}>10张</Option>
                      </Select>,
                    )}
                  </FormItem>
                )
                : ''
            }

            <FormItem {...formItemLayout} required label="时间设置">
              {getFieldDecorator('type', {
                initialValue: current.delayDayNum === null ? 0 : 1,
              })(
                <RadioGroup>
                  <Radio disabled={isDisabled} value={0}>
                    按固定时间
                  </Radio>
                  <Radio disabled={isDisabled} value={1}>
                    按领取日期
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem>

            <FormItem {...formItemLayout} colon={false} label=" ">
              {getFieldValue('type') === 0 ? (
                getFieldDecorator('startEnd', {
                  rules: [{ validator: validataDate }],
                  initialValue: current && [moment(current.startTime), moment(current.endTime)],
                })(<RangePicker disabled={isDisabled} />)
              ) : (
                <div>
                  自领取时
                  {getFieldDecorator('delayDayNum', {
                    rules: [{ required: true, message: '请输入天数' }],
                    initialValue: current.delayDayNum,
                  })(<InputNumber disabled={isDisabled} min={1} precision={0} />)}{' '}
                  天内未使用优惠券自动过期
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券使用人群" required>
              {getFieldDecorator('userRange', {
                rules: [{ required: true, message: '请选择使用条件' }],
                initialValue: (current && current.userRange) || 'ALL',
              })(
                <RadioGroup onChange={onConditions}>
                  <Radio disabled={isDisabled} value="ALL">
                    所有人
                  </Radio>
                  <Radio disabled={isDisabled} value="PART">
                    指定用户
                  </Radio>
                  <Radio disabled={isDisabled} value="NEW">
                    新用户
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem>
            {Conditions === 'PART' ? (
              <FormItem {...formItemLayout} label="上传" required>
                <Button style={{ width: '104px', height: '31px', marginRight: 30 }}>
                  <a style={{ textDecoration: 'none' }} href={testModal} download="模版">
                    下载模板
                  </a>
                  {/* <a style={{ textDecoration: 'none' }} download="模版">
                    下载模板
                  </a> */}
                </Button>
                <Upload
                  fileList={fileLists}
                  // action={handleChange}
                  onChange={onUpload}
                  beforeUpload={file => {
                    handleChange(file);
                    return false;
                  }}
                >
                  <Button type="primary" ghost>
                    <Icon type="upload" /> 上传
                  </Button>
                </Upload>
              </FormItem>
            ) : null}
            <FormItem {...formItemLayout} label="优惠券适用范围" required>
              {getFieldDecorator('rangeTypess', {
                initialValue: (current && current.rangeType) || 'ALL',
              })(
                <RadioGroup onChange={onThes}>
                  <Radio disabled={isDisabled} value="ALL">
                    全场通用
                  </Radio>
                  <Radio disabled={isDisabled} value="CATEGORY">
                    指定类目
                  </Radio>
                  <Radio disabled={isDisabled} value="PRODUCT">
                    指定商品
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem>
            {scope === 'CATEGORY' ? (
              <FormItem {...formItemLayout} label="指定类目" required>
                {getFieldDecorator('status1', {
                  rules: [{ required: true, message: '请选择' }],
                })(
                  <Select
                    mode="multiple"
                    style={{ width: '100%' }}
                    placeholder="请选择类目"
                    onChange={onCategory}
                  >
                    {SelectAll.map((item, value) => {
                      return <Option key={`${JSON.stringify(item)}`}>{item.name}</Option>;
                    })}
                  </Select>,
                )}
              </FormItem>
            ) : null}
            {scope === 'PRODUCT' ? (
              <FormItem {...formItemLayout} label="指定商品" required>
                {getFieldDecorator('userRange11', {
                  rules: [
                    {
                      validator: validatorGeographic,
                    },
                  ],
                  initialValue: tags,
                })(
                  <Fragment>
                    <Spin spinning={keyWord}>
                      <div style={{ background: '#ECECEC', padding: '30px' }}>
                        <div style={{ display: 'flex' }}>
                          <Search
                            placeholder="商品名称/货号"
                            onSearch={onSear}
                            style={{ width: 200 }}
                          />
                          <Select
                            mode="multiple"
                            style={{ width: '100%' }}
                            placeholder="请选择商品"
                            onChange={onSelecthandleChange}
                            style={{ width: 300, marginLeft: 20 }}
                          >
                            {SelectAllSopt.map((item, value) => {
                              return (
                                <Option key={`${JSON.stringify(item)}`}>{item.productName}</Option>
                              );
                            })}
                          </Select>
                          <Button
                            type="primary"
                            style={{
                              margin: '0 20px',
                            }}
                            onClick={onTj}
                          >
                            新增
                          </Button>
                          <Button onClick={onQk}>清空</Button>
                        </div>
                        <div
                          style={{
                            fontSize: 12,
                            fontFamily: 'PingFangSC-Regular,PingFang SC',
                            fontWeight: 400,
                            color: 'rgba(0,0,0,0.25)',
                          }}
                        >
                          购买以下分类商品可使用优惠券抵扣金额，已选中
                          <span
                            style={{
                              color: '#000',
                              fontWeight: 700,
                            }}
                          >
                            {tags.length}
                          </span>
                          个分类
                        </div>
                        <div>
                          {tags.map((tag, index) => {
                            return (
                              <Tag key={tag.description} closable onClose={() => handleClose(tag)}>
                                {tag.productName}
                                {tag.description}
                              </Tag>
                            );
                          })}
                        </div>
                      </div>
                    </Spin>
                  </Fragment>,
                )}
              </FormItem>
            ) : null}
            {/* <FormItem {...formItemLayout} label="优惠券是否支持大礼包" required>
              {getFieldDecorator('forPackage', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: current.forPackage || 'T',
              })(
                <RadioGroup>
                  <Radio disabled={isDisabled} value="T">
                    支持
                  </Radio>
                  <Radio disabled={isDisabled} value="F">
                    不支持
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem> */}
            <FormItem {...formItemLayout} label="优惠券状态" required>
              {getFieldDecorator('status', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: current.status || 'VALID',
              })(
                <RadioGroup>
                  <Radio disabled={isDisabled} value="VALID">
                    有效
                  </Radio>
                  <Radio disabled={typeStatus === 'ALIPAY' ? true : isDisabled} value="INVALID">
                    失效
                  </Radio>
                  {/* <Radio disabled={isDisabled} value="UNASSIGNED">
                    未配大礼包
                  </Radio>
                  <Radio disabled={isDisabled} value="ASSIGNED">
                    已经分配大礼包
                  </Radio> */}
                  <Radio disabled={isDisabled} value="RUN_OUT">
                    已领完
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem>
            {
              typeStatus === 'PACKAGE'
                ? (
                  <FormItem {...formItemLayout} label="是否已分配大礼包" required>
                    {getFieldDecorator('nouse', {})(
                      <p>{packageId ? '已分配大礼包' : '未分配大礼包'}</p>,
                    )}
                  </FormItem>
                )
                : ''
            }
            <FormItem {...formItemLayout} label="优惠券展示说明">
              {getFieldDecorator(
                'displayNote',
                {},
              )(<Input.TextArea placeholder="最多显示12个字" />)}
            </FormItem>
            <div style={{ textAlign: 'center' }}>
              <Button
                onClick={handleCancel}
                style={{ width: 120, height: 40, marginRight: 20 }}
              >
                取消
              </Button>
              {
                typeStatus === 'PACKAGE' && packageId
                  ? ''
                  : (
                    <Button type="primary" htmlType="submit" style={{ width: 120, height: 40 }}>
                      确定
                    </Button>
                  )
              }
            </div>
          </Form>
        </Spin>
        <Modal
          visible={productVisible}
          title="选择商品"
          width={750}
          onOk={onSelectOk}
          onCancel={onShowModal}
        >
          <Spin spinning={props.loading}>
            <div style={{ marginBottom: 20 }}>
              <Input style={{ width: '50%' }} placeholder="输入商品ID" onChange={onInputChan} />
              <Button style={{ marginLeft: 20 }} type="primary" icon="search" onClick={onSearch}>
                查询
              </Button>
            </div>
            <Table
              rowKey="productId"
              dataSource={list}
              columns={Modalcolumns}
              pagination={{
                current: currentTotls,
                pageSize: 10,
                total: Modaltotal,
              }}
              onChange={onIdChang}
              rowSelection={rowSelection}
            />
          </Spin>
        </Modal>
      </Card>
    </PageHeaderWrapper>
  );
});
export default connect(({ coupons, loading }) => ({ ...coupons, loading: loading.models.coupons }))(
  AddList,
);
